package Cordiali_Es2;



import arjuna.JavaSim.Simulation.*;
import arjuna.JavaSim.Distributions.*;

import java.io.IOException;
import java.util.Stack;


import arjuna.JavaSim.Simulation.SimulationException;


public class Recycle extends SimulationProcess {
		
	public UniformStream STime;
	
	private Stack<User> usersQueue = new Stack<User>(); 
	private double to1P,to2P;
//	private User J;

	public Recycle(double toServer1Probab,double toServer2Probab) {
		/*STime = new UniformStream(0, 1);//), 0, 0,0);
		to1P=toServer1Probab;
		to2P=toServer2Probab;*/
		//exitP=1-to1P-to2P;
		//System.out.println(to1P+" - "+to2P);
		this(toServer1Probab, toServer2Probab, null);
	}
	
	public Recycle(double toServer1Probab,double toServer2Probab, SeedsData seeds) {
		if(seeds!=null)
			STime = new UniformStream(0, 1, 0, seeds.MSeed, seeds.LSeed);
		else
			STime = new UniformStream(0, 1, 0 , 0, 0);
		to1P=toServer1Probab;
		to2P=toServer2Probab;
		//exitP=1-to1P-to2P;
		//System.out.println(to1P+" - "+to2P);
	}

	int toS1, toS2, toExit;
	public void run() {		
		try {
			while(true) {
				while(!usersQueue.isEmpty())
				{
					User u = usersQueue.pop();
					double rand = STime.getNumber();
					if(rand<=to1P){ ECommerceShop.Server1.addToQueue(u); toS1++; }
					else if(rand<=to1P+to2P){ ECommerceShop.Server2.addToQueue(u); toS2++; }
					else { ECommerceShop.pool.collectUserStatistics(u); toExit++; }
				}
				Passivate();
			}
		} catch (RestartException e) {
			e.printStackTrace();
		} catch (ArithmeticException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}
	
	public void addToQueue(User u)
	{
		try {
			usersQueue.push(u);
			Activate();
		} catch (ArithmeticException e) {
					
		} catch (SimulationException e) {
			
		} catch (RestartException e) {
			
		}		
	}	
	
	@Override
	public void terminate() {
		
		//System.out.println(toS1+" - "+toS2+" - "+toExit);
		super.terminate();
	}
};
